// Store
import engine from 'store';
export const sessionStorage = engine.createStore([
  require('store/storages/sessionStorage')
]);

/**
 * 角色管理
 * 管理员角色：R000
 * 财务角色：R010
 * CPA角色：R020
 * 信息流角色：R030
 * 设计角色：R040
 * 运营角色：R050
 */
export function isRole(role = "") {
  let _role = sessionStorage.get("user").role;
  if (_role === "R000") return true;
  return _role === role;
}

/**
 * 模块展示控制
 * 合同管理：P010
 * CPA数据管理：P020
 * 信息流管理：P030
 * 批量管理：P050
 * 头条批量管理：P060
 * 推送管理：P070
 * 删除评论: P080
 */
export function isPermission(permission = []) {
  let _permission = sessionStorage.get("user").permission;
  let _role = sessionStorage.get("user").role;
  if (_role === "R000") return true;
  if (_permission) {
    let _permissions = _permission.split(",");
    return permission.every(p => _permissions.indexOf(p) !== -1);
  }
  return false;
}

/**
 * 登录后入口页面
 */
export function getLoginEntry() {
  let map = {
    "P010": "/contract",
    "P020": "/cpa",
    "P030": "/flow",
    "P050": "/advertise",
    "P060": "/toutiao",
    "P070": "/ding",
    "P080":"/comments"
  };
  if (isRole("ROOO")) {
    return map["P020"];
  }
  let _permission = sessionStorage.get("user").permission;
  if (_permission) {
    return map[_permission.split(",")[0]]
  }
  return "";
}

// 获取字符长度
export function getStrLen(str) {
  let count = 0,
    len = String(str).length;
  if (len) {
    for (let i = 0; i < len; i++) {
      if (String(str).charCodeAt(i) > 255) {
        count += 2;
      } else {
        count++;
      }
    }
  }
  return count;
}

// 下拉value对应的label
export function mapOptionLabel(data, value) {
  let item = data.find(item => item.value === value);
  if (item) {
    return item.label;
  }
  return "-";
}

export function mapOptionValue(data, label) {
  let item = data.find(item => item.label === label);
  if (item) {
    return item.id;
  }
  return "-";
}
// 乘 1.001 * 100
export function decimalMultiply(a, b) {
  let scale = Math.pow(10, decimalTotal(a) + decimalTotal(b));
  return Number(String(a).replace(".", "")) * Number(String(b).replace(".", "")) / scale;
}
// 有几位小数
export function decimalTotal(num) {
  if (String(num).indexOf(".") === -1) return 0;
  return String(num).split(".")[1].length;
}
// 校验导入
export function contractBeforeUpload(file) {
  const type = /\.xlsx?$/.test(file.name);
  if (!type) {
    this.$message.error("请上传excel格式的文件");
  }
  this.importLoading = this.$loading({
    lock: true,
    text: "正在导入...",
    spinner: "el-icon-loading",
    background: "rgba(0, 0, 0, 0.7)"
  });
  return type;
}